package com.zto.sch.advance.dubbo.泛化调用;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.rpc.RpcContext;

public class ApiConsumer {

    public static void main(String[] args) throws InterruptedException {

        // 1.创建服务引用对象实例
        ReferenceConfig<GreetingService> referenceConfig = new ReferenceConfig<GreetingService>();
        // 2.设置应用程序信息
        referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer"));
        // 3.设置服务注册中心
        referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));

        //直连测试
        //referenceConfig.setUrl("dubbo://192.168.0.109:20880");

        // 4.设置服务接口和超时时间
        referenceConfig.setInterface(GreetingService.class);
        referenceConfig.setTimeout(5000);

        // 5.设置自定义负载均衡策略与集群容错策略
        referenceConfig.setLoadbalance("myroundrobin");
        referenceConfig.setCluster("myCluster");
        RpcContext.getContext().set("ip", "30.10.67.231");

        // 6.设置服务分组与版本
        referenceConfig.setVersion("1.0.0");
        referenceConfig.setGroup("dubbo");

        // 7.引用服务
        GreetingService greetingService = referenceConfig.get();

        // 8. 设置隐式参数
        // 设置隐式参数，然后服务提供者就可以在服务实现类方法里获取参数值
        RpcContext.getContext().setAttachment("company", "alibaba");

        // 9. 调用服务
        // 同步发起远程调用，然后当前线程会被阻塞直到服务提供方把结果返回
        System.out.println(greetingService.sayHello("world"));

        Thread.currentThread().join();
    }
}